import _ from 'lodash'
import {getDefaultAddress, getAddresses} from "api/addressApi";

export default {
    state: () => ({
        isAddressChosenForOrder: false,
        userAddresses: [],
        defaultAddress: null,
        currentAddress: null
    }),
    getters: {
        isAddressChosenForOrder: state => state.isAddressChosenForOrder,
        userAddresses: state => state.userAddresses,
        defaultAddress: state => state.defaultAddress,
        currentAddress: state => state.currentAddress
    },
    mutations: {
        setIsAddressChosenForOrder(state, isAddressChosenForOrder = false) {
            state.isAddressChosenForOrder = isAddressChosenForOrder
        },
        setUserAddresses(state, addresses = []) {
            state.userAddresses = addresses
        },
        setDefaultAddress(state, address = {}) {
            state.defaultAddress = address
        },
        setCurrentAddress(state, address = {}) {
            state.currentAddress = address
        },
				resetAddress(state,addresses = {}){
					state.userAddresses = []
					state.defaultAddress = null
					state.currentAddress = null
					state.isAddressChosenForOrder =false
				}
    },
    actions: {
        async updateIsAddressChosenForOrder({ commit }, isAddressChosenForOrder = false) {
            commit('setIsAddressChosenForOrder', isAddressChosenForOrder)
        },
        async getUserAddresses({ commit }) {
            const response = await getAddresses()
            commit('setUserAddresses', response.data)
        },
        async getDefaultAddress({ state, commit }) {
            const address = await getDefaultAddress()
            if (_.isEmpty(address)) {return}
            if (state.currentAddress) {
                commit('setDefaultAddress', address)
            } else {
                commit('setDefaultAddress', address)
                commit('setCurrentAddress', address)
            }
        },
        async updateUserAddresses({ commit }, addresses = []) {
            commit('setUserAddresses', addresses)
        },
        async updateCurrentAddress({ commit }, address) {
            commit('setCurrentAddress', address)
        }
    }
}
